<template>
    <div>
        <van-row style="margin-top: 1rem;"> 
            <van-col span="2" >
                <van-icon name="arrow-left" @click="exit" />
            </van-col>
        </van-row>
        <p>群聊</p>
        <van-row >
            <van-col span="16" offset="4">
                <form onSubmit="return false;">
                    
                <textarea id="responseText" disabled style="width: 250px;height: 400px;text-align: center;"></textarea>
                <!-- <input type="text" id="message" name="message" placeholder="这里输入消息" />  -->
                <van-cell-group>
                    <van-field v-model="value" id="message"  placeholder="请输入消息" >
                        <template #button>
                            <van-button type="primary" size="mini" @click="send()">发送消息</van-button>
                        </template>
                    </van-field>
                </van-cell-group>
             
            </form>
            </van-col>
        </van-row>
        
    </div>
</template>

<script>
import { Field } from 'vant';
    export default{
        data(){
        return{
          value:"",
          username:localStorage.getItem("username"),
        }
       },
       methods:{
        send(){
            if(!window.WebSocket){return;}
            if(socket.readyState === WebSocket.OPEN) {
                let message = document.getElementById('message').value;
                socket.send(this.username+"-"+message);
            } else {
                alert("WebSocket 连接没有建立成功！");
            }
        },
        exit(){
                this.$router.go(-1)
        },
       },
       mounted(){
        
       }
    }
     let socket;
        if(window.WebSocket){
            socket = new WebSocket("ws://localhost:8088/ws");
            socket.onmessage = function(event){
                let textarea = document.getElementById('responseText');
                textarea.value += event.data+"\r\n";
            };
            socket.onopen = function(event){
                let textarea = document.getElementById('responseText');
                textarea.value = "聊天群连接成功  \r\n";
            };
            socket.onclose = function(event){
                let textarea = document.getElementById('responseText');
                textarea.value = "聊天群关闭  \r\n";
            };
        } else {
            alert("您的浏览器不支持WebSocket协议！");
        }

        // function send(){
        //     if(!window.WebSocket){return;}
        //     if(socket.readyState === WebSocket.OPEN) {
        //         let message = document.getElementById('message').value;
        //         console.log("打印")
        //         socket.send(message);
        //     } else {
        //         alert("WebSocket 连接没有建立成功！");
        //     }

        // }
</script>